﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Threading.Tasks;
using Microsoft.Phone.Storage;
using wBooks.Entity;
using Windows.Storage;

namespace wBooks
{
    public partial class PivotMainPage : PhoneApplicationPage
    {
        public PivotMainPage()
        {
            InitializeComponent();
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            //List<Books> allXmlDoc = new List<Books>();
            //Books books = new Books();
            //books = XmlHelper.GetBookDetail("Bookshelf/OurLadyTears.xml");
            //allXmlDoc.Add(books);
            //this.listBoxBooks.ItemsSource = allXmlDoc;

            ListAllXMLFile("Bookshelf");
            //ListSDCardFileContents();

            //this.listBoxBooks.ItemsSource = await ListAllXMLFile(); ;
        }

        private async void ListAllXMLFile(string dataFolder)
        {
            //string[] allAuthor = await XmlHelper.GetAllAuthor(dataFolder);
            List<Books> allXmlDoc = new List<Books>();
            // settings
            // same as (ms-appx:///MyFolder/MyFile.txt)
            var _Folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
            _Folder = await _Folder.GetFolderAsync(dataFolder);

            // acquire file
            var _File = await _Folder.GetFilesAsync();
            Books books = new Books();

            foreach (StorageFile file in _File)
            {
                if (file.Path.EndsWith(".xml"))
                {
                    books = XmlHelper.GetBookDetail(dataFolder + "/" + file.Name);
                    allXmlDoc.Add(books);
                }
            }

            this.listBoxBooks.ItemsSource = allXmlDoc;
        }

        //async Task with await
        private async Task ListSDCardFileContents()
        {

            // List the first /default SD Card whih is on the device. Since we know Windows Phone devices only support one SD card, this should get us the SD card on the phone.
            ExternalStorageDevice sdCard = (await ExternalStorage.GetExternalStorageDevicesAsync()).FirstOrDefault();
            if (sdCard != null)
            {
                // Get the root folder on the SD card.
                ExternalStorageFolder sdrootFolder = sdCard.RootFolder;
                if (sdrootFolder != null)
                {
                    // List all the files on the root folder.
                    var files = await sdrootFolder.GetFilesAsync();
                    if (files != null)
                    {
                        foreach (ExternalStorageFile file in files)
                        {
                            if (file.Path.EndsWith(".xml"))
                            {
                                //Do something later
                                //Stream s = await file.OpenForReadAsync();
                                //if (s != null || s.Length == 0)
                                //{
                                //    long streamLength = s.Length;
                                //    StreamReader sr = new StreamReader(s);
                                //    MessageBox.Show(sr.ReadToEnd());
                                //}
                                //else
                                //{
                                //    MessageBox.Show("There were no files in the root folder");
                                //}
                            }
                            else
                            {
                                MessageBox.Show("There were no xml files in the root folder");
                            }
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Failed to get root folder on SD card");
                }
            }
            else
            {
                MessageBox.Show("SD Card not found on device");
                NavigationService.Navigate(new Uri("/ReadBook.xaml?bName=OurLadyTears", UriKind.Relative));
            }
        }

        private void listBoxBooks_SelectionChanged(object sender,
                                         SelectionChangedEventArgs e)
        {
            if (listBoxBooks.SelectedItem != null)
            {
                Books book = (Books)listBoxBooks.SelectedItem;
                listBoxBooks.SelectedItem = null;
                Sessions.CurrentBook.Value = book.FileName;
                //this.NavigationService.Navigate(new Uri("/ReadBook.xaml?bName=" + book.FileName, UriKind.Relative));
                this.NavigationService.Navigate(new Uri("/ReadBook.xaml", UriKind.Relative));
            }
        }
    }
}